<style lang="scss">
.el-form {
  margin-top: 20px;
  margin-left: 20px;
}

.el-form-item {
  margin-bottom: 10px;

  .el-input,
  .el-textarea {
    width: 280px;
  }
}

.compute-number {
  position: absolute;
  top: 0;
  right: -90px;
}
</style>

<template>
  <el-dialog :visible="showDialog" title="新增号段" width="540px" @close="$emit('update:visible', false)">
    <el-form ref="form" :model="form" label-width="100px" :rules="rules" inline>
      <el-form-item label="号段前置：" prop="prefix">
        <el-input v-model="form.prefix" size="mini" />
      </el-form-item>

      <el-form-item label="起始单号：" prop="start">
        <el-input v-model="form.start" size="mini">
          <span slot="prepend">{{ form.prefix }}</span>
        </el-input>
      </el-form-item>

      <el-form-item label="截止单号：" prop="end">
        <el-input v-model="form.end" size="mini">
          <span slot="prepend">{{ form.prefix }}</span>
        </el-input>
        <el-button class="compute-number" type="primary" size="mini" @click="computeTotal">计算数量</el-button>
      </el-form-item>

      <el-form-item label="面单总数：">
        <el-input v-model="form.total" size="mini" disabled />
      </el-form-item>

      <el-form-item label="号段状态：">
        <el-input v-model="form.status" size="mini" />
      </el-form-item>

      <el-form-item label="备注：">
        <el-input v-model="form.remarks" type="textarea" rows="3" />
      </el-form-item>
    </el-form>

    <template slot="footer">
      <div>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import _ from 'lodash'

export default {

  name: 'NumberPoolAddDialog',

  props: {
    visible: {
      required: true,
      type: Boolean
    }
  },

  data() {
    return {
      showDialog: false,

      form: {
        prefix: 'S',
        start: '',
        end: '',
        total: 0,
        status: '',
        remarks: ''
      },

      rules: {
        prefix: [{ required: true, message: '请输入号段前置' }],
        start: [{ required: true, message: '请输入起始单号' }],
        end: [{ required: true, message: '请输入截止单号' }]
      }
    }
  },

  watch: {
    visible() {
      this.showDialog = this.visible
    }
  },

  methods: {
    computeTotal() {
      const start = _.parseInt(this.form.start)
      const end = _.parseInt(this.form.end)

      if (!start || !end) {
        this.$message.error('请输入数字')
        return
      }

      const total = parseInt(this.form.end) - parseInt(this.form.start) + 1

      if (total <= 0) {
        this.$message.error('截止单号必须大于起始单号')
        return
      }

      this.form.total = total
    },

    save() {
      const validate = _.get(this.$refs, 'form.validate')
      if (!_.isFunction(validate)) return

      validate(isPass => {
        if (!isPass) return

        console.log(_.cloneDeep(this.form))
      })
    }
  }

}
</script>
